/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yy.bugzillahelp.action.download;

import com.yy.bugzillahelp.MainFrame;
import com.yy.bugzillahelp.data.ComponentData;
import com.yy.bugzillahelp.data.ProductData;
import com.yy.bugzillahelp.data.VersionData;
import com.yy.bugzillahelp.data.server.ServerData;
import com.yy.bugzillahelp.tool.DecimalTool;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Alan
 */
public class ProductCrawlAction {

//    public static final String[] SERVER = new String[]{"http://66.239.64.109:8099/bugzilla-3.6.2", "alan.zeng@lonnesol.com", "123456"};
    public static final String[] SERVER = new String[]{"http://cn.gobsnet.com:8090/bugzilla", "alan.zeng@lonnesol.com", "turnsys"};
    private static final Logger logger = Logger.getLogger(ProductCrawlAction.class.getName());

    public static void main(String[] args) throws IOException {
        ArrayList<ProductData> searchProducts = searchProducts(MainFrame.CONNECT_DATA);
        for (ProductData productData : searchProducts) {
            logger.log(Level.INFO, productData.toString());
            logger.log(Level.INFO, "");
        }
    }

    public static ArrayList<ProductData> searchProducts(ServerData serverData) {
        logger.log(Level.INFO, "ProductCrawlAction  searchProducts of server:{0}", serverData);
        try {
            Document doc = Jsoup.connect(serverData.getServerUrl() + "/editproducts.cgi"
                    + "?Bugzilla_login=" + URLEncoder.encode(serverData.getUserName(), "utf-8")
                    + "&Bugzilla_password=" + serverData.getPassword()).timeout(30000).get();
            Element body = doc.body();

            Element admin_table = body.getElementById("admin_table");
            Elements children = admin_table.children();
            ArrayList<ProductData> productDatas = parseProductDatas(children.get(0));//tbody
            for (ProductData productData : productDatas) {
                searchProdcutData(serverData, productData);
            }
            return productDatas;
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private static ArrayList<ProductData> parseProductDatas(Element tbody) throws IOException {
        logger.log(Level.INFO, "ProductCrawlAction  parseProductDatas");
        ArrayList<ProductData> productDatas = new ArrayList<ProductData>();

        int produtcIdx = 0;
        Elements trs = tbody.children();
        for (int i = 0; i < trs.size(); i++) {
            if (i == 0) {
                //<editor-fold defaultstate="collapsed" desc="parse table title">
                Element tr = trs.get(i);
                Elements ths = tr.children();
                for (int j = 0; j < ths.size(); j++) {
                    Element th = ths.get(j);
                    String text = th.text();
                    if (text.startsWith("Edit product")) {
                        produtcIdx = j;
                    }
                }
                //</editor-fold>
            } else {
                Element tr = trs.get(i);
                Elements tds = tr.children();

                ProductData productData = new ProductData();
                productData.setId(DecimalTool.formatToString(i, 3));
                if (produtcIdx > -1) {
                    Element product = tds.get(produtcIdx);
                    productData.setName(product.text());
                }
                productDatas.add(productData);
            }
        }

        return productDatas;
    }

    private static void searchProdcutData(ServerData serverData, ProductData productData) throws IOException {
        logger.log(Level.INFO, "ProductCrawlAction  searchProdcutData:{0}", productData.getName());
        Document doc = Jsoup.connect(serverData.getServerUrl() + "/editproducts.cgi"
                + "?Bugzilla_login=" + URLEncoder.encode(serverData.getUserName(), "utf-8")
                + "&Bugzilla_password=" + serverData.getPassword()
                + "&action=edit"
                + "&product=" + URLEncoder.encode(productData.getName(), "utf-8")).timeout(30000).get();
        Element body = doc.body();
        Element bugzilla_body = body.getElementById("bugzilla-body");

        Elements description = bugzilla_body.getElementsByAttributeValue("name", "description");
        productData.setDesc(description.get(0).text());
        Elements is_active = bugzilla_body.getElementsByAttributeValue("name", "is_active");
        productData.setActive(is_active.get(0).attr("checked").equals("checked"));
        Elements allows_unconfirmed = bugzilla_body.getElementsByAttributeValue("name", "allows_unconfirmed");
        productData.setAllowsUnconfirmed(allows_unconfirmed.get(0).attr("checked").equals("checked"));

        searchComponentData(serverData, productData);
        searchVersionData(serverData, productData);
    }

    private static void searchComponentData(ServerData serverData, ProductData productData) throws IOException {
        logger.log(Level.INFO, "ProductCrawlAction  searchComponentData:{0}", productData.getName());
        Document doc = Jsoup.connect(serverData.getServerUrl() + "/editcomponents.cgi"
                + "?Bugzilla_login=" + URLEncoder.encode(serverData.getUserName(), "utf-8")
                + "&Bugzilla_password=" + serverData.getPassword()
                + "&product=" + URLEncoder.encode(productData.getName(), "utf-8")).timeout(30000).get();
        Element body = doc.body();

        Element admin_table = body.getElementById("admin_table");
        Elements trs = admin_table.getElementsByTag("tr");
        for (int i = 1; i < trs.size(); i++) {
            Elements tds = trs.get(i).children();
            ComponentData componentData = new ComponentData();
            componentData.setProductId(productData.getId());
            componentData.setId(productData.getId() + "_" + DecimalTool.formatToString(i, 3));
            componentData.setProductName(productData.getName());
            componentData.setName(tds.get(0).text().trim());
            componentData.setDesc(tds.get(1).text().trim());
            componentData.setDefaultAssignTo(tds.get(2).text().trim());
            productData.addComponent(componentData);
        }
    }

    private static void searchVersionData(ServerData serverData, ProductData productData) throws IOException {
        logger.log(Level.INFO, "ProductCrawlAction  searchVersionData:{0}", productData.getName());
        Document doc = Jsoup.connect(serverData.getServerUrl() + "/editversions.cgi"
                + "?Bugzilla_login=" + URLEncoder.encode(serverData.getUserName(), "utf-8")
                + "&Bugzilla_password=" + serverData.getPassword()
                + "&product=" + URLEncoder.encode(productData.getName(), "utf-8")).timeout(30000).get();
        Element body = doc.body();

        Element admin_table = body.getElementById("admin_table");
        Elements trs = admin_table.getElementsByTag("tr");
        for (int i = 1; i < trs.size(); i++) {
            Elements tds = trs.get(i).children();
            VersionData versionData = new VersionData();
            versionData.setProductId(productData.getId());
            versionData.setId(productData.getId() + "_" + DecimalTool.formatToString(i, 3));
            versionData.setProductName(productData.getName());
            versionData.setName(tds.get(0).text().trim());
            versionData.setActive(true);
//            versionData.setActive(tds.get(1).text().trim().equalsIgnoreCase("yes"));
            productData.addVersion(versionData);
        }
    }
}
